<template>
    <el-dialog :close-on-click-modal="false"  ref="dialogform" :title="addEditName + title" :visible.sync="dialogVisible" width="80%"
        :before-close="handleClose">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
            <el-row :gutter="20">
                <el-col :span="12">
                <el-form-item label="案例名称" prop="caseName">
                    <el-input class="w100p" v-model="ruleForm.caseName" clearable placeholder="请输入案例名称" />
                </el-form-item>
                <el-form-item label="选择疾病" prop="diseaseBankId">
                    <el-select class="w100p"  v-model="ruleForm.diseaseBankId"
                        placeholder="请选择疾病" filterable clearable>
                        <el-option v-for="item, index in diseaseList" :key="index" :label="item.diseaseName"
                            :value="item.diseaseBankId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="疾病症状" prop="mainSymptoms">
                    <el-input class="w100p" v-model="ruleForm.mainSymptoms" clearable type="textarea" :rows="2"
                        placeholder="请输入特征描述" maxlength="300" show-word-limit />
                </el-form-item>
                <el-form-item label="预防方法" prop="preventionMethod">
                    <el-input class="w100p" v-model="ruleForm.preventionMethod" clearable type="textarea" :rows="2"
                        placeholder="请输入特征描述" maxlength="300" show-word-limit />
                </el-form-item>
                <el-form-item label="治疗方法" prop="therapeuticMethod">
                    <el-input class="w100p" v-model="ruleForm.therapeuticMethod" clearable type="textarea" :rows="2"
                        placeholder="请输入特征描述" maxlength="300" show-word-limit />
                </el-form-item>
                <el-form-item label="特征图片">
                    <UpLoadImage :limit="2" v-if="dialogVisible && resetUpLoadImage" @getFileIdList="getFileIdList"
                        :isUrl="true" :fileUrlList="fileIdList">
                    </UpLoadImage>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="选择坐标" class="w100p">
                    <baidu-map class="map" :center="center" :zoom="zoom" :scroll-wheel-zoom="true"
                        map-type="BMAP_HYBRID_MAP" @click="setCenterPoint" @load="handleMapLoad">
                        <bm-marker :position="{ lng: center.lng, lat: center.lat }" :dragging="false" />
                        <bm-control>
                            <bm-auto-complete v-model="keyword" :sug-style="{ zIndex: 999999 }">
                                <el-input v-model="keyword" type="text" placeholder="请输入地名关键字"
                                    style="background-color:#003947;" clearable>
                                    <i slot="prefix" class="el-input__icon el-icon-search"></i>
                                </el-input>
                            </bm-auto-complete>
                        </bm-control>
                        <bm-local-search :keyword="keyword" :auto-viewport="true" :select-first-result="true"
                            :panel="false" />
                    </baidu-map>
                    <div v-show="ruleForm.regionName" style="text-align: left;">
                        {{ ruleForm.regionName + ruleForm.provinceName + ruleForm.cityName +
        ruleForm.areaName }}
                    </div>
                </el-form-item>
            </el-col>
            </el-row>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
    </el-dialog>
</template>
<script>
import diseaseCaseManagement from '@/api/diseaseBankManagement/diseaseCaseManagement.js';
import UpLoadImage from "@/components/UpLoadImage";
import { addressList } from '@/utils/address_new'
export default {
    components: { UpLoadImage },
    props: {
        addEditFlag: {
            type: String,
            default: () => {
                return 'add'
            }
        },
        data: {
            type: Object,
            default: () => {
                return {}
            }
        },
        title: {
            type: String,
            default: () => {
                return '操作表单'
            }
        },
        dialogVisible: {
            type: Boolean,
            default: () => {
                return false
            }
        },
        diagnosisItemList: {
            type: Array,
            default: () => {
                return []
            }
        },
        diseaseList: {
            type: Array,
            default: () => {
                return []
            }
        },
    },
    data() {
        return {
            center: { lng: 120.230648, lat: 30.811543 },
            zoom: 22,
            Baidu_BMap: null,
            keyword: "",
            regionList: ['华北地区', '东北地区', '华东地区', '华中南地区', '西南地区', '西北地区', '特别地区'],
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() > Date.now();
                },
                shortcuts: [{
                    text: '今天',
                    onClick(picker) {
                        picker.$emit('pick', new Date());
                    }
                }, {
                    text: '昨天',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24);
                        picker.$emit('pick', date);
                    }
                }, {
                    text: '一周前',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', date);
                    }
                }]
            },
            addEditName: '添加',
            addEditApi: '',
            ruleForm: {},
            resetUpLoadImage: true,
            fileIdList: [],
            rules: {
                diseaseBankId: [
                    { required: true, message: "请选择", trigger: ["change", "blur"] }
                ],
                mainSymptoms: [
                    { required: true, message: "请选择", trigger: ["change", "blur"] }
                ],
                caseName: [
                    { required: true, message: "请输入", trigger: ["change", "blur"] }
                ],
                diagnosisItemSymbolNo: [
                    { required: true, message: "请输入", trigger: ["change", "blur"] }
                ],
                diagnosisItemId: [
                    { required: true, message: "请选择", trigger: ["change", "blur"] }
                ],
                diagnosisItemSymbolDesc: [
                    { required: true, message: "请输入", trigger: ["change", "blur"] }
                ],
                fileIdList: [
                    { required: true, message: "请上传图片", trigger: ["change", "blur"] }
                ],
                preventionMethod: [
                    { required: true, message: "请输入", trigger: ["change", "blur"] }
                ],
                therapeuticMethod: [
                    { required: true, message: "请输入", trigger: ["change", "blur"] }
                ],
            },
        }
    },
    computed: {

    },
    watch: {
        dialogVisible(v) {
            v && this.initData()
        }
    },

    mounted() { },
    methods: {
        initData() {
            if (this.addEditFlag == 'add') {
                this.resetForm();
                this.addEditApi = diseaseCaseManagement.add;
                this.addEditName = '添加';
            } else if (this.addEditFlag == 'edit') {
                this.ruleForm = { ...this.data };
                this.fileIdList = this.data.imgList || []
                console.log(this.fileIdList)
                this.$set(this.ruleForm, 'fileIdList', this.fileIdList);
                this.addEditApi = diseaseCaseManagement.edit;
                this.addEditName = '编辑';
            }
            this.jumpToPoint()
        },
        
        handleMapLoad(e) {
            console.log(e)
            this.Baidu_BMap = e
        },
        setCenterPoint(e) {
            let { point } = e
            this.center.lng = point.lng;
            this.center.lat = point.lat;
            console.log(point)
            this.$set(this.ruleForm, "latitude", point.lat);
            this.$set(this.ruleForm, "longitude", point.lng);
            this.getAddress(point)
        },
        jumpToPoint() {
            if (this.addEditFlag == 'edit') {
                let { latitude, longitude } = JSON.parse(JSON.stringify(this.ruleForm));
                console.log(this.formData)
                if(!longitude||!latitude){
                this.center = { lng: 120.230648, lat: 30.811543 }
                }else{
                    this.center = { lng: longitude || 120.230648, lat: latitude || 120.230648 }
                }
            } else {
                this.center = { lng: 120.230648, lat: 30.811543 }
            }
        },
        getAddress(p) {
            const BMap = window.BMap;
            const geocoder = new BMap.Geocoder();
            const point = new BMap.Point(p.lng, p.lat);
            const that = this;
            geocoder.getLocation(point, result => {
                if (result) {
                    let provinceCode = that.findCodeByName(addressList, result.addressComponents.province)
                    this.address = {
                        provinceName: result.addressComponents.province,
                        provinceCode: provinceCode,
                        cityName: result.addressComponents.city,
                        cityCode: that.findCodeByName(addressList, result.addressComponents.city),
                        areaName: result.addressComponents.district,
                        areaCode: that.findCodeByName(addressList, result.addressComponents.district),
                        regionName: this.regionList[Number(provinceCode[0]) + 1],
                        regionCode: provinceCode[0]
                    };
                    this.ruleForm = {
                        ...this.ruleForm,
                        ...this.address
                    }
                } else {
                    alert('无法获取地址信息');
                }
            });
        },
        findCodeByName(data, name) {
            for (const item of data) {
                if (item.name == name) {
                    return item.code;
                }
                if (item.children) {
                    const result = this.findCodeByName(item.children, name);
                    if (result) {
                        return result;
                    }
                }
            }
            return null; // 如果没有找到，返回null  
        },
        getFileIdList(data) {
            console.log(data.fileIdList)
            this.$set(this.ruleForm, 'fileIdList', data.fileIdList || [])
        },
        //提交表单
        submitForm() {
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    console.log(this.ruleForm)
                    this.addEditApi({
                        ...this.ruleForm,
                        fileUrlList: this.ruleForm.fileIdList?this.ruleForm.fileIdList.toString():''
                    }).then(res => {
                        let msg = res.code == 1 ? '操作成功' : '操作失败'
                        this.$message[res.code == 1 ? 'success' : 'warning'](res.message || msg)
                        res.code == 1 && this.cancel();
                    }).catch(err => {
                        this.$message.error(err)
                    })
                } else {
                    return false;
                }
            })
        },
        //重置
        resetForm() {
            this.fileIdList = [];
            this.ruleForm = {};
            this.keyword = '';
            this.$refs.ruleForm && this.$refs.ruleForm.resetFields()
        },
        //取消关闭
        cancel() {
            this.resetForm()
            this.$emit("closeDialog")
        },
        handleClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => { this.resetForm(); this.cancel() })
                .catch(_ => { });
        }
    }
};
</script>
<style lang="scss" scoped>
.line {
    border-bottom: 1px solid #e6e6e6;
}

.icon {
    font-size: 20px;
    line-height: 29px;
    cursor: pointer;
}

::v-deep .noLabel {
    .el-form-item {
        .label {
            display: none;
        }

        .el-form-item__content {
            margin: 0;
        }
    }
}

.map {
    height: 400px;
    width: 100%;
}
</style>